import { Effect, Reducer } from 'umi';
import { getCommentList, getPageViews } from '@/services';
import { IPageComment, IPageItem } from '@/types';

export interface PageModelState {
  pageListItem: IPageItem;
  pageCommentList: IPageComment[];
  pageCommentLength: number;
}

export interface PageModelStateType {
  namespace: 'page';
  state: PageModelState;
  effects: {
    getPageViews: Effect;
    getCommentList: Effect;
  };
  reducers: {
    save: Reducer<PageModelState>;
  };
}

const PageModel: PageModelStateType = {
  namespace: 'page',

  state: {
    pageListItem: {} as IPageItem,
    pageCommentList: [],
    pageCommentLength: 0,
  },

  effects: {
    *getPageViews({ payload }, { call, put }) {
      const result = yield call(getPageViews, payload);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            pageListItem: result.data,
          },
        });
      }
    },
    *getCommentList({ payload }, { call, put }) {
      const result = yield call(getCommentList, payload);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            pageCommentList: result.data[0],
            pageCommentLength: result.data[1],
          },
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default PageModel;
